﻿using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using QuickGet.Core.Models;
using QuickGet.Core.Services;

namespace QuickGet.Endpoints
{
    public static class DownloadEndpoints
    {
        public static IEndpointRouteBuilder MapDownloadEndpoints(this IEndpointRouteBuilder endpoints)
        {
            var group = endpoints.MapGroup("/download");

            group.MapGet("/file", DownloadFile).WithName(nameof(DownloadFile));

           return endpoints;
        }

        public static async Task<Results<PhysicalFileHttpResult, NotFound>> DownloadFile(
            [FromQuery] string token, [FromQuery] string? filename, 
            [FromServices] IFileDownloadService service, 
            [FromServices] IOperationCancellation operationCancellation)
        {
            var filePath = await service.GetFilePathAsync(token);

            if(filePath is not null && File.Exists(filePath))
            {
                operationCancellation.Token.ThrowIfCancellationRequested();

                return TypedResults.PhysicalFile(filePath, "application/octet-stream", filename ?? $"{Guid.NewGuid()}.nupkg");
            }

            return TypedResults.NotFound();
        }
    }
}
